<template>
  <div class="medicine">
    <!-- Breadcrumb 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>医院后台</el-breadcrumb-item>
      <el-breadcrumb-item>人员信息</el-breadcrumb-item>
      <el-breadcrumb-item>患者信息</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row style="margin-bottom: 1%; margin-left: 1%">
      <!-- 已就诊按钮 -->
      <el-button :class="['custom-filter-btn', { 'is-active': statusFilter === '已就诊' }]" size="medium" type="success" round @click="filterByStatus('已就诊')"> 已就诊 </el-button>

      <!-- 已预约按钮 -->
      <el-button :class="['custom-filter-btn', { 'is-active': statusFilter === '已预约' }]" size="medium" round type="warning" @click="filterByStatus('已预约')"> 已预约 </el-button>

      <!-- 搜索患者的文本框 -->
      <el-input prefix-icon="el-icon-search" placeholder="请输入姓名查询" v-model="searchKeyword" clearable style="width: 180px; height: 28px; right: 20px; position: absolute"></el-input>
    </el-row>
    <el-card shadow="never" border="false">
      <!-- 卡片头部 -->
      <template #header>
        <div class="header">
          <span>共 {{ patientLength }} 条记录</span>
          <el-button icon="el-icon-plus" size="small" type="info" round @click="dialogVisible = true" style="background-color: #8b8989; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)"
            >添加患者</el-button
          >

          <!-- 添加患者对话框 -->
          <el-dialog title="添加患者" :visible.sync="dialogVisible" width="40%" @close="dialogVisible = false">
            <el-form ref="addPatientForm" :model="newPatient" label-width="25%">
              <el-form-item label="患者序号">
                <el-input v-model="newPatient.patientID" style="width: 150px"></el-input>
              </el-form-item>
              <el-form-item label="患者姓名">
                <el-input v-model="newPatient.name" style="width: 150px"></el-input>
              </el-form-item>
              <el-form-item label="就诊状态">
                <el-select v-model="value2" placeholder="请选择">
                  <el-option v-for="item in conditions" :key="item.value2" :label="item.label2" :value="item.value2"> </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="性别">
                <el-select v-model="value3" placeholder="请选择">
                  <el-option v-for="item in gender" :key="item.value3" :label="item.label3" :value="item.value3"> </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="手机号">
                <el-input v-model="newPatient.phone" style="width: 150px"></el-input>
              </el-form-item>
              <el-form-item label="挂号科室">
                <el-select v-model="value" placeholder="请选择">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="挂号类别">
                <el-select v-model="value1" placeholder="请选择">
                  <el-option v-for="item in department" :key="item.value1" :label="item.label1" :value="item.value1"> </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="time" label="挂号时间" class="time-picker-item">
                <el-col :span="7">
                  <el-date-picker type="date" placeholder="选择日期" v-model="newPatient.time" style="width: 150px"></el-date-picker>
                </el-col>
                <el-col class="line" :span="1">--</el-col>
                <el-col :span="11">
                  <el-time-picker placeholder="选择时间" v-model="newPatient.time" style="width: 150px"></el-time-picker>
                </el-col>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitNewPatient">确定</el-button>
            </span>
          </el-dialog>
        </div>
      </template>

      <!-- 卡片的内容 -->
      <el-table stripe :data="filteredPatients" style="width: 100%" :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
        <el-table-column prop="patientID" label="患者序号" fixed></el-table-column>
        <el-table-column prop="name" label="患者姓名"></el-table-column>
        <el-table-column prop="sex" label="性别"></el-table-column>
        <el-table-column prop="department" label="挂号科室"> </el-table-column>
        <el-table-column prop="type" label="挂号类别"> </el-table-column>
        <el-table-column prop="time" label="挂号时间"> </el-table-column>
        <el-table-column prop="status" label="就诊状态">
          <template slot-scope="scope">
            <div>
              <i :class="['el-icon', scope.row.status === '已就诊' ? 'el-icon-circle-check' : 'el-icon-remove-outline']"></i>
              <span :style="{ color: scope.row.status === '已就诊' ? 'green' : scope.row.status === '已预约' ? '#ecbd12' : 'inherit' }">
                {{ scope.row.status }}
              </span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="phone" label="手机号"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" icon="el-icon-delete" style="color: red" @click="deletePatient(scope.row.patientID)">删除</el-button>
            <el-button
              v-if="scope.row.status === '已预约'"
              @click="handleCheckIn(scope.$index)"
              type="text"
              size="mini"
              icon="el-icon-check"
              :disabled="scope.row.checkedIn"
              :style="scope.row.checkedIn ? 'color: gray;' : ''"
              >签到</el-button
            >
            <el-button v-else-if="scope.row.checkedIn" type="text" size="small" icon="el-icon-remove" disabled>已签到</el-button>
            <el-button v-else type="text" size="small" icon="el-icon-remove" disabled>已签到</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>

//导入 vuex 中辅助函数
import { mapState, mapGetters, mapActions } from 'vuex';
export default {
  name: 'patient',

  data() {
    return {
      patientLength:0,
      // 新增状态筛选条件，默认显示所有
      statusFilter: '',
      input: '',
      searchKeyword: '',
      value: '',
      value1: '',
      value2: '',
      value3: '',
      // 添加患者对话框控制
      dialogVisible: false,
      newPatient: {
        patientID: '',
        name: '',
        sex: '',
        department: '',
        type: '',
        time: '',
        status: '',
        phone: '',
      },
      form: {
        data1: '',
        data2: '',
      },
      options: [
        { value: '内科', label: '内科' },
        { value: '外科', label: '外科' },
        { value: '妇产科', label: '妇产科' },
        { value: '儿科', label: '儿科' },
      ],
      department: [
        { value1: '急诊', label1: '急诊' },
        { value1: '初诊', label1: '初诊' },
        { value1: '复诊', label1: '复诊' },
      ],
      gender: [
        { value3: '女', label3: '女' },
        { value3: '男', label3: '男' },
      ],
      conditions: [
        { value2: '已预约', label2: '已预约' },
        { value2: '已就诊', label2: '已就诊' },
      ],
    };
  },

  computed: {
    ...mapState('patient', ['patients', 'currentPage', 'pageSize']),
    ...mapGetters('patient', ['patientCount', 'changeDate']), //从store中导入
    ...mapState('patient', ['filteredNurses']), // 从store中导入过滤后的护士列表

    // 修改filteredPatients计算属性以包含搜索过滤
    filteredPatients() {
      let patientsToFilter = this.patients;

      // 根据状态筛选
      if (this.statusFilter) {
        patientsToFilter = patientsToFilter.filter(patient => patient.status === this.statusFilter);
      }

      // 根据搜索关键词筛选
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        patientsToFilter = patientsToFilter.filter(patient => {
          return patient.name.toLowerCase().includes(keyword);
        });
      }
      this.patientLength = patientsToFilter.length
      return patientsToFilter;
    },
  },
  mounted() {
    this.patientLength = this.patients.length;
  },
  methods: {
    deletePatient(patientID) {
      this.$confirm('此操作将永久删除该换着信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 调用删除医生的 action
          this.$store
            .dispatch('patient/DELETE_PATIENT', patientID)
            .then(() => {
              this.$message({
                type: 'success',
                message: '删除成功!',
              });
            })
            .catch(() => {
              this.$message({
                type: 'error',
                message: '删除失败，请重试!',
              });
            });
        })
        .catch(() => {});
    },

    // 按钮点击事件处理
    filterByStatus(status) {
      if (this.statusFilter === status) {
        // 如果当前点击的状态与已选状态相同，则清空筛选条件，恢复默认
        this.statusFilter = '';
      } else {
        // 否则，设置新的筛选条件
        this.statusFilter = status;
      }
    },

    // 提交新患者信息
    submitNewPatient() {
      this.newPatient.department = this.value; // 假设value是从科室下拉中获取的
      this.newPatient.type = this.value1;
      this.newPatient.status = this.value2;
      this.newPatient.sex = this.value3; // 从挂号类别下拉中获取
      // 时间处理，确保time字段格式正确
      this.newPatient.time = this.formatDateTime(this.newPatient.time); // 假设这是一个处理时间的函数
      this.$refs.addPatientForm.validate(valid => {
        if (valid) {
          // 提交至 Vuex
          this.addPatient(this.newPatient)
            .then(() => {
              this.$message({
                message: '添加患者成功',
                type: 'success',
                duration: 2000,
              });
              this.dialogVisible = false;
              this.newPatient = {};
            })
            .catch(error => {
              this.$message.error('添加患者失败，请稍后重试');
              console.error(error);
            });
        }
      });
    },
    formatDateTime(dateTime) {
      if (dateTime instanceof Date) {
        return dateTime.getFullYear() + '-' + (dateTime.getMonth() + 1) + '-' + dateTime.getDate() + '-' + dateTime.getHours() + ':' + dateTime.getMinutes();
      } else {
        console.error('dateTime is not a Date object');
        return '';
      }
    },

    // 使用 mapActions 引入或直接调用 Vuex 中的添加患者 action
    ...mapActions('patient', ['addPatient']),
    handleCheckIn(index) {
      this.$store
        .dispatch('patient/updatePatientStatus', { index, newStatus: '已就诊', checkedIn: true })
        .then(() => {
          this.$message({
            message: '患者签到成功',
            type: 'success',
            duration: 2000,
          });
        })
        .catch(error => {
          this.$message.error('签到失败，请稍后重试');
          console.error(error);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.medicine {
  .el-row {
    position: relative;
  }
  //Breadcrumb 面包屑样式
  .el-breadcrumb {
    margin-top: 10px;
    margin-bottom: 25px;
    z-index: 1;
  }
  //卡片样式
  .el-card {
    margin-top: 25px;
    //卡片头部样式
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-right: 16px;
    }
    //分页样式
    .el-pagination {
      margin-top: 20px;
      text-align: center;
    }
  }
  // 已预约/已就诊按钮样式
  .button-group button {
    transition: background-color 0.3s ease; // 保持原有的平滑过渡效果
  }

  .custom-filter-btn {
    &.el-button:not(.is-active):not(:hover) {
      // 特定类名下的按钮，非激活状态且鼠标未悬停时的颜色恢复
      background-color: #fff; // 或者你希望的默认背景色
      border-color: lightgray; // 边框颜色恢复
      color: inherit; // 文字颜色恢复
      box-shadow: 0 2px 12px 0 rgba(192, 193, 189, 0.558);
    }
  }
  /* 设置图标颜色 */
  .el-table .el-table__body .cell .el-icon-circle-check {
    color: green;
  }
  .el-table .el-table__body .cell .el-icon-remove-outline {
    color: #ecbd12;
  }
}
</style>